package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.feignclient.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.atguigu.yygh.vo.order.SignInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

@Transactional(rollbackFor = Exception.class)
@Service
public class HospitalServiceImpl implements HospitalService {
    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private DictFeignClient dictFeignClient;
    @Resource
    private HospitalSetService hospitalSetService;

    /**
     * 3、上传医院
     * 医院编号是平台分配的，全局唯一，上传医院接口可以多次调用，如果存在相同编号是更新
     *
     * @param paramMap
     */
    @Override
    public void saveHospital(Map<String, Object> paramMap) {
        // 把参数map集合--->JSONO字符串  | JSONO字符串转换为Java对象--> hospital
        String stringMap = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(stringMap, Hospital.class);
        // 查询mogodb的数据,判断是否存在数据
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        // 如果不存在, 进行添加
        if (null != targetHospital) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            // 如果存在, 进行修改
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }

    }


    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        //System.out.println("查询医院接口hospital = " + hospital);
        return hospital;

    }

    @Override
    public Page<Hospital> getHospitalPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 分页处理
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 创建实体对象进行转换
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        hospital.setIsDeleted(0);

        // 创建匹配器,也就是如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        // 创建实例查询
        Example<Hospital> example = Example.of(hospital, matcher);

        // 调用查询方法
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        // 调用feign
        // hospitalPage.getTotalElements()
        hospitalPage.getContent().stream().forEach(item -> {
            this.getPackHospital(item);
        });

        return hospitalPage;
    }

    /**
     * 更新医院的上线状态
     *
     * @param hospitalId
     * @param status
     */
    @Override
    public void updateStatus(String hospitalId, Integer status) {
        if (0 == status || 1 == status) {
            Hospital hospital = hospitalRepository.findById(hospitalId).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }

    }

    /**
     * 查查医院详情信息
     *
     * @param hospitalId
     * @return
     */
    @Override
    public Map<String, Object> showHospDetailById(String hospitalId) {
        Map<String, Object> mapHosp = new HashMap<>();
        Hospital hospital = hospitalRepository.findById(hospitalId).get();
        Hospital packHospital = this.getPackHospital(hospital);
        // 封装查询结果
        mapHosp.put("hospital", packHospital);
        mapHosp.put("bookingRule", packHospital.getBookingRule());
        // 不需要重复返回
        packHospital.setBookingRule(null);
        return mapHosp;
    }

    /**
     * 根据hoscode获取医院的名称
     *
     * @param hoscode
     * @return
     */
    @Override
    public String getHospitalNameByHoscode(String hoscode) {
        // 调用查询方法
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        // 结果判断
        if (ObjectUtils.isEmpty(hospital)) {
            return "对不起,查无此院...";
        }
        String hospitalHosname = hospital.getHosname();
        // 返回数据
        return hospitalHosname;
    }

    @Override
    public List<Hospital> getHospListByHosName(String hosname) {
        List<Hospital> hospitalList = hospitalRepository.findHospListByHosnameLike(hosname);
        // 结果判断
        if (ObjectUtils.isEmpty(hospitalList)) {
            throw new YyghException(ResultCodeEnum.FAIL);
        }

        return hospitalList;
    }

    /**
     * // 根据医院编号查询医院信息
     *
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> showHospDetailByHoscode(String hoscode) {
        Map<String, Object> resultMap = new HashMap<>();
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        Hospital packHospital = this.getPackHospital(hospital);
        // 封装查询结果
        resultMap.put("hospital", packHospital);
        resultMap.put("bookingRule", packHospital.getBookingRule());
        // 不需要重复返回
        packHospital.setBookingRule(null);

        return resultMap;
    }

    @Override
    public SignInfoVo getSignInfoVoByHoscode(String hoscode) {

        // 封装查询条件
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode", hoscode);
        HospitalSet hospitalSet = hospitalSetService.getOne(queryWrapper);

        // 封装签名信息
        SignInfoVo signInfoVo = new SignInfoVo();
        signInfoVo.setApiUrl(hospitalSet.getApiUrl());
        signInfoVo.setSignKey(hospitalSet.getSignKey());

        return signInfoVo;
    }

    /**
     * 整合openFegin远程接口调用
     *
     * @param hospital
     * @return
     */
    public Hospital getPackHospital(Hospital hospital) {

        // 调用feign接口中的方法
        String hosTypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityCodeString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        // 封装结果
        hospital.getParam().put("hosTypeString", hosTypeString);
        hospital.getParam().put("fullAddress", provinceString + cityCodeString + districtString);
        return hospital;
    }


}
